package com.wuzihao.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuzihao.reggie.entity.User;
import com.wuzihao.reggie.mapper.UserMapper;
import com.wuzihao.reggie.service.UserService;
import com.wuzihao.reggie.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    UserService userService;

    @Override
    public void sendSms(User user, HttpSession session) {
        String mobile = user.getPhone();
//        SmsUtils smsUtils = new SmsUtils();
//        //生成验证码
//        String str = UUID.randomUUID().toString().replaceAll("-","").substring(0,6);
//        String code = "code:" + str;
//        smsUtils.sendSms(mobile,code);
        String code = "code:1234";
        session.setAttribute(mobile,code);
        log.info(session.getAttribute("19599960285").toString());
    }

    @Override
    public User login(Map map, HttpSession session) {
        String mobile = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取验证码
        String sessionCode = (String) session.getAttribute(mobile);
        sessionCode = sessionCode.substring(5);
        if(sessionCode != null && sessionCode.equals(code)){
            //验证码比对正确，登录成功
            User userEntity = userService.getOne(new QueryWrapper<User>().eq("phone", mobile));
            if(userEntity == null){
                //用户第一次登陆则注册一个用户
                User user = new User();
                user.setPhone(mobile);
                user.setStatus(1);
                userService.save(user);
                session.setAttribute("user",user.getId());
                //返回新创建的用户
                return user;
            }
            session.setAttribute("user",userEntity.getId());
            //用户不是第一次登录，返回该用户
            return userEntity;
        }
        //验证码错误
        return null;
    }

}
